module.exports = {
    APIError: function (code, message) {
        this.code = code || 'internal:unknown_error'
        this.message = message || ''
    },
    /**
     * @param(pathPrefix)
     * 中间件层级
     */
    restify: (pathPrefix) => {
        pathPrefix = pathPrefix || '/'
        return async (ctx, next) => {
            if (ctx.request.url.indexOf(pathPrefix)===0) {
                ctx.json = (data) => {
                    ctx.response.type = 'application/json'
                    ctx.response.body = data
                }
                try {
                    await next()
                } catch (error) {
                    ctx.response.status = 302
                    ctx.response.type = 'application/json'
                    ctx.response.body = {
                        code: error.code || 'internal:unknown_error',
                        message: error.message || ''
                    }
                }
            } else {
                await next()
            }
        }
    }
}
